<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\TextbookRequest;
use App\Models\V1\Major;
use App\Models\V1\NewArrival;
use App\Models\V1\Textbook;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Log;
class TextbooksController extends Controller
{
    /**
     * 显示班级数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $codes = $this->getEnrollmentCodes();
        $data['codes'] = $codes;
        $arrival_code = $this->getArrivalCodes();
        $data['arrival_code'] = $arrival_code;
        return view('v1.newData.textbooks',$data);
    }

    /**
     * 获取生活用品数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的班级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');
        $arrival_code = $request->get('arrival_code');

        $from_select = $request->get('from_select');

        if ($from_select == false && empty($arrival_code)) {
            $arrival_code = $this->getArrivalCodes();
        }

        // 获取符合查询条件的班级数据
        $data = $this->getTextbookList($currentPage, $rows, $arrival_code);
        $formatList = array();
        if (!$data->isEmpty()) {
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['remark'] = $item['remark'];
                    $formatItem['count'] = $item['count'];
                    $formatItem['unit'] = $item['unit'];
//                    $formatItem['majors'] = $item['majors'];
                    $majors = $this->formatMajor($item['majors'],$item['arrival_code']);
                    $formatItem['majors'] = $majors;
//                    $formatItem['relate_information'] = $this->formatMajor($item['relate_information'],1);
                    $formatItem['arrival_code'] = $item['arrival_code'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['msg'] = '加载数据成功';
            }
        }else{
            $count = 0;
            $response['msg'] = '暂无数据';
            $formatList = [];
        }
        $response['code'] = 0;
        $response['count'] = $count;
        $response['data'] = $formatList;
        return $response;
    }

    /**
     * 进入单条班级数据显示界面（适用于新增addData、编辑editData、查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')) {
            case 'addData':
                return view('v1.form.textbook_item', $data);
                break;
            case 'viewData':
                $code = $request->input('code');
                $arrival_code = $request->input('arrival_code');
                $textbook = $this->getTextbookByCode($code,$arrival_code);
                $textbook['majors'] = $this->formatMajor($textbook['majors'],$arrival_code);
                $data['textbook'] = $textbook;
                return view('v1.form.textbook_item', $data);
                break;
            case 'selectMajors':
                $code = $request->get('code');
                $arrival_code = $request->get('arrival_code');
                $data['code'] = $code;
                $textbook = $this->getTextbookByCode($code,$arrival_code);
                $data['arrival_code'] = $arrival_code;
                $majors = $this->getMajorList($arrival_code);
                $selectedMajor = json_decode($textbook->majors, true);
                if (empty($selectedMajor)) {
                    $selectedMajor = array();
                }
                $data['majors'] = $majors;
                $data['selectedMajor'] = $selectedMajor;
                return view('v1.newData.textbook_major',$data);
                break;
        }
    }

    /**
     * 显示新生教材数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser->getAttribute('code');

        return view('v1.form.upload_excel', $data);
    }

    /***
     * 选择领用专业
     */
    public function selectMajors(Request $request) {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '选择领用专业失败！',
        ];
        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '教材代码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);
            // 新增信息
            $successFlag = $this->handleUpdateMajor($request);
            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '选择领用专业成功！';
            }
        }

        return $response;
    }


    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新生教材[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['name'] = 'bail|required';
            $rules['count'] = 'bail|required';
            $rules['unit'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '教材代码不能为空';
            $messages['name.required'] = '教材名称不能为空';
            $messages['count.required'] = '人均派发数量不能为空';
            $messages['unit.required'] = '数量单位不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '新生教材[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 删除班级基本信息
     *
     * @param DailyUseRequest $request
     * @return array
     */
    public function deleteData(TextbookRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '教材代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateTextbook($request);

            // 删除班级信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '教材代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除班级基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '教材批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '教材批量删除成功！';
            }
        }

        return $response;
    }

    /**
     * 更新报到流程基本信息(单元格)
     *
     * @param ReportProcessRequest $request
     * @return array
     */
    public function updateCellData(TextbookRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '教材代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateTextbook($request);

            // 更新部门信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '教材代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }



    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新班级信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');
        $arrival_codes = $request->input('arrival_code');
        if ($bBatch) { // 批量删除
            for ($i=0; $i<count($where);$i++) {
                $code = $where[$i];
                $arrival_code = $arrival_codes[$i];
                $rspObj = Textbook::where('code', $code)
                    ->where('arrival_code',$arrival_code)
                    ->delete();
            }
        } else { // 单条删除
            $rspObj = Textbook::where('code', $where)
                ->where('arrival_code',$arrival_codes)
                ->delete();
        }

        return $rspObj;
    }

    /****
     * @param Request $request
     * @param $bCell 是否为单元格修改数据
     * @return mixed
     */
    public function handleUpdate(Request $request, $bCell) {
        $where = $request->input('code');
        $arrival_code = $request->input('arrival_code');
        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组

            $updateData = [
                'name' => $request->input('name'),
                'remark' => $request->input('remark'),
                'count' => $request->input('count'),
                'unit' => $request->input('unit'),
                'majors' => $request->input('majors'),
            ];
        }

        $rspObj = Textbook::where('code', $where)
            ->where('arrival_code',$arrival_code)
            ->update($updateData);

        return $rspObj;
    }

    /***
     * 选择领用专业
     * @param Request $request
     * @param $bCell
     * @return mixed
     */
    public function handleUpdateMajor(Request $request) {
        $code = $request->input('code');
        $arrival_code = $request->input('arrival_code');

        $allKeys = $request->keys();
        $majors = array();
        foreach ($allKeys as $allKey) {
            $value = $request->get($allKey);
            if ($value === 'on') {
                array_push($majors,$allKey);
            }
        }
        $updateData = [
            'majors' => json_encode($majors),
        ];
        $rspObj = Textbook::where('code', $code)
            ->where('arrival_code',$arrival_code)
            ->update($updateData);
        return $rspObj;
    }

    /***
     * 处理添加
     * @param Request $request
     * @return mixed
     */
    public function handleAdd(Request $request) {
        $arrival_code = $this->getArrivalCodes();

        // 拼装新增数据数组
        $insertData = [
            'code' => $request->input('code'),
            'name' => $request->input('name'),
            'remark' => isset($request['remark'])?$request->input('remark'):'',
            'count' => isset($request['count'])?$request->input('count'):'',
            'unit' => isset($request['unit'])?$request->input('unit'):'',
            'arrival_code' => $arrival_code,
        ];
        $rspObj = Textbook::updateOrCreate(['code'=>$request->input('code')],$insertData);
        return $rspObj;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的迎新列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getTextbookList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = Textbook::orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = Textbook::where('arrival_code', 'like', '%' . $keywords . '%')
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /***
     * 根据code获取生活用品信息
     * @param $code
     * @return mixed
     */
    private function getTextbookByCode($code,$arrival_code)
    {
        $major = Textbook::where('code', $code)->where('arrival_code',$arrival_code)->first();
        return $major;
    }

    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn',true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }

    /***
     * 获取专业详情
     */
    private function getMajorByCode($code,$arrival_code){
        return  Major::where('arrival_code', $arrival_code)
            ->where('code',$code)
            ->first();
    }


    /***
     * 获取专业
     */
    private function getMajorList($arrival_code){
       return  Major::where('arrival_code', $arrival_code)
           ->where('parent_code','!=','0')
           ->select('name','code')
           ->get();
    }
    /**
     * 获取所有招生年份
     *
     * @param $code
     * @return mixed|string
     */
    private function getEnrollmentCodes()
    {
        $codes = NewArrival::all()->pluck('code')->toArray();
        return $codes;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新班级信息验证请求
     *
     * @param Request $request
     */
    private function validateTextbook(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }


    /**
     * 格式专业信息
     *
     * @param $val
     * @return string
     */
    private function formatMajor($majors,$arrival_code)
    {
        $result = '';
        if (empty($majors)) {
            return $result;
        }else{
            $content = json_decode($majors, true);
            foreach ($content as $item){
                $major = $this->getMajorByCode($item,$arrival_code);
                if (empty($major)) {
                    $result .= ' ';
                }else {
                    $name = $major['name'];
                    $result .= ' '.$name;
                }
            }
        }
        return $result;
    }
}
